<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./socket.io.js"></script>
</head>
<body>
        <h1>聊天室</h1>
        <input type="text" name="" id="sendTxt">
        <button id="sendBtn">发送</button>
</body>

<script>
      function showMessage(data,type){
        var div = document.createElement('div');
        div.innerHTML = data;
        if(type == "enter"){
            div.style.color  = "blue"
        }else if(type == "leave"){
            div.style.color  = "red"
        }
        document.body.appendChild(div)
    }
    var socket = io('ws://localhost:3000');
    document.getElementById("sendBtn").onclick = function(e){
        var txt = document.getElementById("sendTxt").value;
        if(txt == ""){
            alert("不能空")
            return
         }
         socket.emit('message',txt)
    }
    socket.on('enter',function(data){
        showMessage(data,'enter')
    })  
    socket.on('message',function(data){
        showMessage(data,'message')
    }) 
    socket.on('leave',function(data){
        showMessage(data,'leave')
    })           
</script>
</html>